package com.ruoyi.common.order.service.impl;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.OrderNumberTypeEnum;
import com.ruoyi.common.order.service.OrderNumberService;
import com.ruoyi.common.order.strategy.OrderNumberStrategyFactory;
import com.ruoyi.common.utils.OrderNumberUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.paramters.domain.Parameter;
import com.ruoyi.paramters.mapper.ParameterMapper;
import org.springframework.stereotype.Service;

@Service
public class OrderNumberServiceImpl implements OrderNumberService {

    // 订单前缀管理 Mapper
    private ParameterMapper parameterMapper;
    // 订单后缀的策略模板工厂
    private OrderNumberStrategyFactory strategyFactory;

    public OrderNumberServiceImpl(ParameterMapper parameterMapper, OrderNumberStrategyFactory strategyFactory) {
        this.parameterMapper = parameterMapper;
        this.strategyFactory = strategyFactory;
    }

    @Override
    public String reBuildOrderNumber(String date, String code) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 获取订单号前缀
        String prefix = orderNumberPrefix(code, loginUser.getCompanyId());
        // 获取订单号
        String orderNumber = OrderNumberUtils.generateOrderNumber(date);
        // 获取订单号后缀
        String suffix = strategyFactory.queryExecute(code).buildOrderNumberSuffix(date, loginUser.getCompanyId());
        return prefix +"-"+ orderNumber +"-"+ suffix;
    }

    /**
     * 获取对应的订单号前缀
     * @param code 订单类型
     * @param companyId 公司ID
     * @return 结果
     */
    private String orderNumberPrefix(String code, Long companyId) {
        Parameter parameter = parameterMapper.selectParameterById(companyId);
        return OrderNumberTypeEnum.fromCode(code).getPrefix(parameter);
    }
}